package com.ruoyi.faceplus.helper;

import com.arcsoft.face.FaceEngine;
import com.ruoyi.faceplus.domain.ImageFeature;
import com.ruoyi.faceplus.domain.UserFace;
import com.ruoyi.faceplus.face.FaceServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
public class FaceDetectHelper {

    private FaceEngine mFaceEngine;

    @Autowired
    private FaceServer faceServer;

    /**
     * 人脸识别，返回人脸数据
     * @param file
     * @return
     */
    public UserFace execute(File file) {
        try {
            mFaceEngine = faceServer.faceEnginePoll();
            // 获取人脸引擎
            boolean hasEngine = false;
            if (mFaceEngine != null) hasEngine = true;
            while (!hasEngine) {
                mFaceEngine = faceServer.faceEnginePoll();
                if (mFaceEngine != null) hasEngine = true;
            }

            if (mFaceEngine == null) {
                System.out.println("============================================ 切图识别 没有拿到人脸引擎 ============");
                return null;
            }

            // 虹软人脸比对结果
            List<ImageFeature> imageFeatures = faceServer.faceExtract(file, mFaceEngine);
            if (imageFeatures != null && imageFeatures.size() > 0) {
                for (ImageFeature imageFeature : imageFeatures) {
                    // 比对人脸用户
                    UserFace userFace = faceServer.faceSearch(imageFeature.getFaceFeature(), imageFeature.getMaskInfo().getMask(), false, mFaceEngine);
                    if (userFace != null) return userFace;
                }
            }

            return null;
        } catch (Exception e) {
            System.out.println("人脸识别，返回人脸数据 异常："+e.getMessage());
            return null;
        } finally {
            if (mFaceEngine != null) faceServer.faceEngineOffer(mFaceEngine);
            // 删除文件
            file.delete();
            file.deleteOnExit();
        }
    }
}
